package com.w08e.waai.controller;

import com.w08e.waai.dto.TradingStrategyResponse;
import com.w08e.waai.service.BinanceDataService;
import com.w08e.waai.service.TradingScheduledService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 交易策略控制器
 * @Author: 智能交易策略系统
 * @Date: 2025/1/14
 */
@RestController
@RequestMapping("/api/trading")
@RequiredArgsConstructor
@Slf4j
public class TradingController {
    
    private final TradingScheduledService tradingScheduledService;
    private final BinanceDataService binanceDataService;
    
    /**
     * 手动触发策略分析
     */
    @PostMapping("/analyze")
    public ResponseEntity<TradingStrategyResponse> manualAnalyze() {
        try {
            log.info("收到手动分析请求");
            TradingStrategyResponse strategy = tradingScheduledService.manualTriggerAnalysis();
            return ResponseEntity.ok(strategy);
        } catch (Exception e) {
            log.error("手动分析失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 发送测试消息到钉钉群
     */
    @PostMapping("/test-message")
    public ResponseEntity<Map<String, String>> sendTestMessage() {
        try {
            log.info("收到测试消息发送请求");
            tradingScheduledService.sendTestMessage();
            
            Map<String, String> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "测试消息发送成功");
            response.put("timestamp", LocalDateTime.now().toString());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("发送测试消息失败", e);
            
            Map<String, String> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", e.getMessage());
            response.put("timestamp", LocalDateTime.now().toString());
            
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取最新K线数据
     */
    @GetMapping("/kline-data")
    public ResponseEntity<Map<String, Object>> getKlineData(@RequestParam(defaultValue = "ETHUSDT") String symbol) {
        try {
            log.info("收到获取K线数据请求，交易对: {}", symbol);
            String klineData = binanceDataService.getLatest24HourKlineData(symbol);
            Double currentPrice = binanceDataService.getCurrentPrice(symbol);
            
            Map<String, Object> response = new HashMap<>();
            response.put("symbol", symbol);
            response.put("currentPrice", currentPrice);
            response.put("dataLength", klineData != null ? klineData.length() : 0);
            response.put("data", klineData);
            response.put("timestamp", LocalDateTime.now().toString());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取K线数据失败", e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", e.getMessage());
            response.put("timestamp", LocalDateTime.now().toString());
            
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取系统状态
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getSystemStatus() {
        Map<String, Object> status = new HashMap<>();
        
        try {
            // 检查数据获取功能
            String testData = binanceDataService.getLatest24HourKlineData("ETHUSDT");
            status.put("dataService", testData != null && !testData.isEmpty() ? "正常" : "异常");
            
            // 系统基本信息
            status.put("timestamp", LocalDateTime.now().toString());
            status.put("scheduledTask", "每30分钟执行");
            status.put("tradingSymbol", "ETHUSDT");
            status.put("aiApiConfigured", "是");
            status.put("dingTalkConfigured", "是");
            
            return ResponseEntity.ok(status);
            
        } catch (Exception e) {
            log.error("获取系统状态失败", e);
            status.put("error", e.getMessage());
            return ResponseEntity.internalServerError().body(status);
        }
    }
    
    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, String>> health() {
        Map<String, String> health = new HashMap<>();
        health.put("status", "UP");
        health.put("service", "Trading Strategy AI System");
        health.put("timestamp", LocalDateTime.now().toString());
        return ResponseEntity.ok(health);
    }
    
    /**
     * 查看缓存状态
     */
    @GetMapping("/cache-status")
    public ResponseEntity<Map<String, Object>> getCacheStatus() {
        try {
            String cacheInfo = binanceDataService.getCacheStatus();
            
            Map<String, Object> response = new HashMap<>();
            response.put("cacheInfo", cacheInfo);
            response.put("timestamp", LocalDateTime.now().toString());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取缓存状态失败", e);
            
            Map<String, Object> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", e.getMessage());
            
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 手动清理所有数据文件
     */
    @PostMapping("/cleanup-data")
    public ResponseEntity<Map<String, String>> cleanupData() {
        try {
            log.info("收到手动清理数据请求");
            binanceDataService.manualCleanupAllData();
            
            Map<String, String> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "数据清理完成");
            response.put("timestamp", LocalDateTime.now().toString());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("手动清理数据失败", e);
            
            Map<String, String> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", e.getMessage());
            response.put("timestamp", LocalDateTime.now().toString());
            
            return ResponseEntity.internalServerError().body(response);
        }
    }
} 